package view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;

/**
 * Class is responsible for exception frame.
 * every exception that occurs in the system will be report to that class.
 * Frame contains: 	data field   - show all exceptions reported
 * 					clear button - clear exception reported list
 * 					Save to file - button enable choosing file to save 
 * 					Help button  - that open the help frame. 
 */
public class ErrorFrame extends JFrame
{
	/**
	 * Serial version ID - for serialization
	 */
	private static final long serialVersionUID = -1222418353483663659L;

	public static  ErrorFrame currentErrorFrame = null;
	private		   JSplitPane splitPaneV;
	private		   JPanel     panelDesc;
	private		   JPanel	  panelActions;
	private static JTextArea  txtArea;

	
	/**
	 * C'tor - 
	 * Define the frame.
	 */
	public ErrorFrame()
	{
		/* set the frame title */
		setTitle( "FW Exception List" );
		JPanel topPanel = new JPanel();
		topPanel.setLayout( new BorderLayout() );
		getContentPane().add( topPanel );

		// Create the panels
		createPanelDesc();
		createPaneActions();

		// Create a splitter pane
		splitPaneV = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
		topPanel.add( splitPaneV, BorderLayout.CENTER );
		splitPaneV.setLeftComponent( panelDesc);
		splitPaneV.setRightComponent(panelActions);
	
		pack();
		setLocationRelativeTo(null);
		setVisible(false);
		
		currentErrorFrame = this;
	}
	
	/**
	 * Create the panel of the exceptions descriptions  (the upper panel)
	 * @param  N\A
	 * @return N\A
	 */
	public void createPanelDesc()
	{
		panelDesc = new JPanel();
		txtArea = new JTextArea();
		txtArea.setEditable(false);
		txtArea.setLineWrap(true);
		txtArea.setWrapStyleWord(true);
		
		panelDesc.setLayout( new BorderLayout() );
        panelDesc.setPreferredSize( new Dimension( 800, 500) );
        panelDesc.setMinimumSize( new Dimension( 100, 50 ) );
        panelDesc.add(txtArea, BorderLayout.CENTER);
	}
	

	/**
	 * Create the panel of the operations (the lower panel)
	 * @param  N\A
	 * @return N\A
	 */	
	public void createPaneActions()
	{ 
		/*Creaet the panel's buttons */
		JButton clearButton = new JButton( "Clear" );
		JButton saveButton = new JButton( "Save To File" );
		JButton helpButton = new JButton( "Help" );

		panelActions = new JPanel();
		panelActions.setLayout(new BoxLayout(panelActions, BoxLayout.X_AXIS));
		panelActions.add(clearButton);
		panelActions.add(saveButton);
		panelActions.add(helpButton);
		
		/* create action listener for clear button - 
		 * click on this button will clear all the exceptions list */
		clearButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				Clear();
			}
		}
		);		
		
		/* create action listener for save button - 
		 * click on this button will open file chooser for choosing a file to 
		 * save into all the  exceptions list */
		saveButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				SaveToFile();
			}
		}
		);		

		/* create action listener for help button - 
		 * click on this button will open the help frame */
		helpButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				HelpFrame.currentHelpFrame.ShowDesc(Globals.ERROR);
			}
		}
		);		
	}
	
	/**
	 * Enable saving the help description into file 
	 * @param  N\A
	 * @return N\A
	 */	
	private void SaveToFile() 
	{
		JFileChooser chooser = new JFileChooser();
		try
		{
			/* Show chooser file window to the user for choosing file to save into */
			if(chooser.showSaveDialog(this) ==JFileChooser.APPROVE_OPTION)
			{
				String strFilePath = chooser.getSelectedFile().getPath();
				FileWriter fileOutput = new FileWriter(strFilePath);

				/* Write all errors into the file */ 
				String allText = txtArea.getText() ;
				StringTokenizer st = new StringTokenizer(allText,"\n") ;
				while (st.hasMoreTokens()) 
					fileOutput.write(st.nextToken() + "\r\n");
				
				fileOutput.close();
			}
		}
		catch (IOException ex)
		{
			JOptionPane.showMessageDialog(this, "The action can not be done\n" +
						ex.getMessage());
		}
	}

	/**
	 * Clear all the exceptions list
	 * @param  N\A
	 * @return N\A
	 */	
	private void Clear()
	{
	    String[]  choices = {"YES", "NO"};
	       
	    /* Certifying that the user really want to clear all exceptions*/
		int response = JOptionPane.showOptionDialog(
                null                       // center over parent
              , "This action will clean all exceptions log.\n Do you still want to perform this action?" // message
              , "clear exceptions"             // title in titlebar
              , JOptionPane.YES_NO_OPTION  // Option type
              , JOptionPane.PLAIN_MESSAGE  // messageType
              , null                       // icon
              , choices                    // Options
              , "NO"    // initial value
           );
		
		if(response == 0)
		{
			txtArea.setText("");
		}
	}
	
	/**
	 * Add exception to the exceptions list, and show a message box with the 
	 * exception description
	 * @param  String strErr - the description of the exception that occurs
	 * @param  JFrame frame - the frame that the exception occurs on
	 * @return N\A
	 */
	public static void AddError(String strErr, JFrame frame)
	{
		if(frame == null)
		{
			frame = new JFrame();
		}
		
		/* Show message box swith the exception description */
		JOptionPane.showMessageDialog(frame, strErr);
		Date now = new Date();

		/* add the exception description to the exceptions list*/
		txtArea.append(SimpleDateFormat.getDateTimeInstance().format(now) +
					" -- "+  strErr + "\n");
	}

	/**
	 * Returns current frame if exists, ales creates it.
	 * @return logger frame
	 */
	public static ErrorFrame getInctance()
	{
		if(currentErrorFrame == null)
		{
			currentErrorFrame = new ErrorFrame();
		}
		
		return currentErrorFrame;
	}
}
